package com.david.core.view

import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import com.david.core.R

/**可设置高／宽比的framelayout*/
public class RatioFrameLayout:FrameLayout {
    /**
     * height/width ratio
     */
    private var ratio = 0f

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        if (attrs != null) {
            init(context, attrs)
        }
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        if (attrs != null) {
            init(context, attrs)
        }
    }

    private fun init(context: Context, attrs: AttributeSet) {
        // 加载自定义属性的值
        val typedArray = context.obtainStyledAttributes(attrs,
            R.styleable.RatioFrameLayout)
        // 根据属性id获取属性值, 方式: R.styleable.名称_属性
        ratio = typedArray.getFloat(R.styleable.RatioFrameLayout_ratio, 0f)
        // 回收TypedArray, 释放内存
        typedArray.recycle()
    }

    fun setRatio(ratio: Float) {
        this.ratio = ratio
        requestLayout()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var widthMeasureSpec = widthMeasureSpec
        var heightMeasureSpec = heightMeasureSpec
        if (ratio != 0f) {
            //获取宽度的模式和尺寸
            var widthSize = MeasureSpec.getSize(widthMeasureSpec)
            val widthMode = MeasureSpec.getMode(widthMeasureSpec)
            //获取高度的模式和尺寸
            var heightSize = MeasureSpec.getSize(heightMeasureSpec)
            val heightMode = MeasureSpec.getMode(heightMeasureSpec)


            //宽确定，高不确定
            if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY && ratio != 0f) {
                heightSize = (widthSize * ratio).toInt()//根据宽度和比例计算高度
                heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY)
            } else if (widthMode != MeasureSpec.EXACTLY && (heightMode == MeasureSpec.EXACTLY) and (ratio != 0f)) {
                widthSize = (heightSize / ratio).toInt()
                widthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY)
            }
        }

        //必须调用下面的两个方法之一完成onMeasure方法的重写，否则会报错
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }
}